/**
 * @Project RSLsXWG
 * @Author Tran Manh Hung
 * @Email: hungtmit@gmail.com | tmh@xwebgate.com
 * @Copyright © 2011 TMH. All rights reserved
 * @Createdate Feb 18, 2011
 * @Createtime 10:55:50 AM
 */

package com.gigalaxy.game.card
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	public class Deck extends EventDispatcher implements IEventDispatcher
	{
		/**
		 * Number of cards in deck<br />
		 */
		public static const SIZE:uint = 52;

		public var cardsSet:Vector.<Card>;

		protected var cardFrom:int;

		protected var cardTo:int;

		public var numCards:int;

		public function Deck(cardFrom:int = 1, cardTo:int = 13)
		{
			this.cardFrom = cardFrom;
			this.cardTo = cardTo;

			numCards = (cardTo - cardFrom + 1) * 4;

			cardsSet = new Vector.<Card>;

			var cardIndex:int = 0;

			for (var i:int = 0; i < 4; i++)
			{
				for (var j:int = cardFrom - 1; j < cardTo; j++)
				{
					cardsSet[cardIndex] = new Card(Card.valueFromInt(j + 1), Card.suitFromInt(i + 1));
					cardIndex++;
				}
			}
		}

		/**
		 * Randomize card set in deck
		 */
		public function shuffle():void
		{
			for (var i:int = 0; i < numCards; i++)
			{
				cardsSet[i].weight = Math.random();
			}

			cardsSet.sort(cmpCard);
		}

		/**
		 * A negative return value specifies that A appears before B in the sorted sequence.
		 * A return value of 0 specifies that A and B have the same sort order.
		 * A positive return value specifies that A appears after B in the sorted sequence
		 */
		private function cmpCard(a:Card, b:Card):int
		{
			var ret:int = 0;

			if (a.weight < b.weight)
			{
				ret = 1;
			}
			else if (a.weight > b.weight)
			{
				ret = -1;
			}

			return ret;
		}

		public function toStringExt(prefix:String = ""):String
		{
			var ret:String = prefix + "[ ";

			for (var i:int = 0; i < numCards; i++)
			{
				ret += cardsSet[i].toStringExt() + " ";
			}

			ret += "]";

			return ret;
		}
	}
}
